package top.kikt.book.core.handlers

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler


@Suppress("ClassName")
class `31Xs` : BaseBookHandler() {
    override val host: String = "www.31xs.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.select("#info > h1").text()
        val authorScr = document.select("#info > p:nth-child(2)").text()
        val author = try {
            authorScr.split("：")[1]
        } catch (e: Exception) {
            authorScr
        }
        logger.info("name = $name, author = $author")

        return BookMetaEntity(name, url, url, author).apply {
            val cover = document.select("#fmimg > img").attr("src") ?: return@apply
            this.coverImageUrl = url.toHttpUrl().resolve(cover).toString()
        }
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val result = ArrayList<ChapterMetaEntity>()
        val menus = document.select("#list > dl > dd > a")
        val httpUrl = menuUrl.toHttpUrl()
        for ((index, menu) in menus.withIndex()) {
            val title = menu.text()
            val url = menu.attr("href")
            val chapterUrl = httpUrl.resolve(url)

            result.add(
                ChapterMetaEntity(title, index, chapterUrl.toString(), menu)
            )
        }
        return result
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val document = chapterMetaEntity.toDocument() ?: return null
        val content = document.select("#content > p")
        val sb = StringBuilder()
        for (element in content) {
//            sb.append("　　")
            sb.appendLine(element.text())
        }
        return ChapterEntity(chapterMetaEntity.name, chapterMetaEntity.index, sb.toString())
    }

}